package com.leetcode.problems051;

import java.util.*;

/**
 * https://leetcode-cn.com/problems/n-queens/
 * @Date 2021/12/09 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    private boolean[] cols = null;

    private boolean[] leftDia = null;

    private boolean[] rightDia = null;

    public List<List<String>> solveNQueens(int n) {
        cols = new boolean[n];
        //左对角线（下标：col - row + n - 1）
        leftDia = new boolean[2 * n - 1];
        //右对角线（下标：col + row）
        rightDia = new boolean[2 * n - 1];
        List<Integer> res = new ArrayList<>();
        List<List<Integer>> ans = new ArrayList<>();
        solveNQueens(0,n,n,res,ans);
        return generateNQueensRes(ans);
    }

    private void solveNQueens(int row,int n,int q,List<Integer> res,List<List<Integer>> ans){
        if(q == 0){
            ans.add(new ArrayList<>(res));
            return;
        }
        if(row == n){
            return;
        }
        for (int i = 0; i < n; i++) {
            if(cols[i] || leftDia[i - row + n - 1] || rightDia[row + i]){
                continue;
            }
            cols[i] = true;
            leftDia[i - row + n - 1] = true;
            rightDia[row + i] = true;
            res.add(i);
            solveNQueens(row + 1,n,q - 1,res,ans);
            res.remove(res.size() - 1);
            cols[i] = false;
            leftDia[i - row + n - 1] = false;
            rightDia[row + i] = false;
        }
    }

    private List<List<String>> generateNQueensRes(List<List<Integer>> list){
        List<List<String>> ans = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<Integer> resolve = list.get(i);
            int N = resolve.size();
            List<String> res = new ArrayList<>();
            for (Integer r : resolve) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int j = 0; j < N; j++) {
                    if(j == r){
                        stringBuilder.append("Q");
                    }else{
                        stringBuilder.append(".");
                    }
                }
                res.add(stringBuilder.toString());
            }
            ans.add(res);
        }
        return ans;
    }



    public static void main(String[] args) {
        int n = 1;
        System.out.println(new Solution().solveNQueens(n));
    }
}
